<template>
  <div class="column-detail-page w-690">
    <div class="row mb-4 border-bottom pb-4 align-items-center" v-if="column">
      <div class="col-3 text-center" v-if="column.avatar">
        <img
          :src="column.avatar.fitUrl"
          :alt="column.title"
          class="rounded-circle border w-100"
        />
      </div>
      <div :class="{ 'col-9': column.avatar }">
        <h4>{{ column.title }}</h4>
        <p class="text-muted">{{ column.description }}</p>
      </div>
    </div>
    <post-list :list="list"></post-list>
    <button v-if="!isShow" :class="loadMoreClass" @click="loadMore()">
      加载更多
    </button>
  </div>
</template>

<script lang='ts'>
import { defineComponent, computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { GlobalDataProps, ColumnProps } from '@/store'
import PostList from '../components/PostList.vue'
import { addColumnAvatar } from '../helper'

type ColumnType = ColumnProps | undefined;

const loadMoreClass = [
  'btn',
  'btn-outline-primary',
  'mt-2',
  'mb-5',
  'mx-auto',
  'd-block',
  'w-25'
]

export default defineComponent({
  components: {
    PostList
  },
  setup () {
    const route = useRoute()

    const store = useStore<GlobalDataProps>()

    const currentId = route.params.id

    const column = computed(() => {
      const currentColumn: ColumnType = store.getters.getColumnById(currentId)
      if (currentColumn) {
        addColumnAvatar(currentColumn, 100, 100)
      }
      return currentColumn
    })

    const list = computed(() => {
      return store.getters.getPostsByCid(currentId)
    })

    onMounted(() => {
      store.dispatch('fetchColumn', currentId)
      store.commit('clearPosts')
      store
        .dispatch('fetchPosts', {
          cid: currentId,
          currentPage: currentPage.value
        })
        .then((res) => {
          currentPage.value++
          totalCount.value = res.data.count
        })
    })

    const currentPage = ref(1)
    const totalCount = ref(0)

    const isShow = computed(() => {
      return Math.ceil(totalCount.value / 5) === currentPage.value - 1
    })

    const loadMore = () => {
      store
        .dispatch('fetchPosts', {
          cid: currentId,
          currentPage: currentPage.value
        })
        .then((res) => {
          currentPage.value++
          totalCount.value = res.data.count
        })
    }

    return {
      column,
      list,
      loadMoreClass,
      isShow,
      loadMore
    }
  }
})
</script>

<style scoped>
.w-690 {
  width: 690px;
  margin: 0 auto;
}
</style>
